package cn.easyutil.deploy.executor;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import cn.easyutil.deploy.util.RemoteUtil;

import java.util.List;

/**
 * 远程指令执行
 */
public class RemoteCommandExecutor extends AbstractExecutor{

    private String ip;
    private String username;
    private String password;
    private int port = 22;
    private RemoteUtil remoteUtil;

    public RemoteCommandExecutor(String ip, String username, String password) {
        this.ip = ip;
        this.username = username;
        this.password = password;
        this.remoteUtil = new RemoteUtil(ip,port,username,password);
    }

    public RemoteCommandExecutor(String ip, int port, String username, String password) {
        this.ip = ip;
        this.username = username;
        this.password = password;
        remoteUtil = new RemoteUtil(ip,port,username,password);
    }

    public RemoteCommandExecutor(RemoteUtil remoteUtil) {
        this.remoteUtil = remoteUtil;
    }

    @Override
    public void exec(List<String> cmds) {
        exec(() -> exec(appandCmds(cmds)));
    }

    private String appandCmds(List<String> command){
        if (command == null || command.size() == 0) {
            return null;
        }
        StringBuffer sb = new StringBuffer();
        for (String s : command) {
            if(sb.length() != 0){
                sb.append(" && ");
            }
            sb.append(s);
        }
        return sb.toString();
    }

    private void exec(String cmd){
        Session session = null;
        Connection conn = null;
        try {
            conn = remoteUtil.connect();
            session =  conn.openSession();
            session.execCommand(cmd);
            print(session.getStdout());
            print(session.getStderr());
            if(isWaitFor){
                synchronized (this){
                    this.wait();
                }
            }
        }catch (Exception e){
            throw new RuntimeException(e);
        }finally {
            if(conn != null){
                conn.close();
            }
            if(session != null){
                session.close();
            }
        }
    }

    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }
}
